package com.buss.customer.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.buss.core.persistence.ResultList;
import com.buss.customer.dao.CustomerClassDao;
import com.buss.customer.model.CustomerClass;
import com.buss.customer.service.CustomerClassService;

@Service
public class CustomerClassServiceImpl implements CustomerClassService {

	@Autowired
	private CustomerClassDao classDao;
	
	@Override
	public CustomerClass saveClass(CustomerClass customerClass) {
		customerClass.setSubClasses(0);
		if(customerClass.getParentId() != 0){
			CustomerClass tmpClass = classDao.loadClass(customerClass.getParentId());
			if(tmpClass != null){
				tmpClass.setSubClasses(tmpClass.getSubClasses() + 1);
				classDao.editClass(tmpClass);
			}
		}		
		return classDao.saveClass(customerClass);
	}

	@Override
	public void editClass(CustomerClass customerClass) {
		CustomerClass tmpClass = classDao.loadClass(customerClass.getId());
		if(tmpClass.getParentId() != customerClass.getParentId()){
			if(customerClass.getParentId() != 0){
				classDao.updateSubClasses(customerClass.getParentId(), 1);
			}
			if(tmpClass.getParentId() != 0){
				classDao.updateSubClasses(tmpClass.getParentId(), -1);
			}
		}
		classDao.editClass(customerClass);
	}

	@Override
	public void removeClass(Long[] ids) {
		for(Long id : ids){
			CustomerClass customerClass = classDao.loadClass(id);
			classDao.updateSubClasses(customerClass.getParentId(), -1);
		}
		classDao.removeClass(ids);
	}

	@Override
	public CustomerClass loadClass(Long id) {
		return classDao.loadClass(id);
	}

	@Override
	public ResultList<CustomerClass> queryByParentId(String companyId,
			Long parentId, String name) {
		
		return classDao.queryByParentId(companyId, parentId, name);
	}

	@Override
	public List<CustomerClass> queryByParentIdToAll(String companyId,
			Long parentId) {
		List<CustomerClass> list = queryByParentId(companyId, parentId,null).getData();
		List<CustomerClass> tmpList = new ArrayList<CustomerClass>();
		for(CustomerClass customerClass : list){
			tmpList.add(customerClass);
			getChildCustomerClass(companyId,customerClass.getId(),tmpList);
		}
		return tmpList;
	}

	private void getChildCustomerClass(String companyId,Long parentId,List<CustomerClass> tmpList){
		List<CustomerClass> list = queryByParentId(companyId, parentId, null).getData();
		for(CustomerClass customerClass : list){
			tmpList.add(customerClass);
			getChildCustomerClass(companyId, customerClass.getId(), tmpList);
		}
	}
	
}
